package com.sourcespro.mybatis.service.impl;

import com.sourcespro.mybatis.TreeUtil;
import com.sourcespro.mybatis.dao.TreeMapper;
import com.sourcespro.mybatis.entity.Tree;
import com.sourcespro.mybatis.service.TreeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 分类
 *
 * @author 张浩伟
 * @date 2018/07/09
 */
@Service
public class TreeServiceImpl implements TreeService {

    private static final Logger logger = LoggerFactory.getLogger(TreeServiceImpl.class);

    @Autowired
    private TreeMapper mapper;

    //@LRTreeAdd(tableName = "tree")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Tree add(Tree record) {

        /*Integer pid = record.getPid();
        //如果是第一层：
        if (pid == 0) {
            //查询第一层最大的右值  maxRight
            int maxLv1Val = mapper.maxLv1Val();

            //新的数据的左右值为
            record.setLft(maxLv1Val + 1);
            record.setRgt(maxLv1Val + 2);
            record.setLevel(0);
            record.setIds("");

        }
        // 如果非第一层：pId！=0
        else {
            Tree parent = mapper.findById(pid);
            // 获取要添加节点父节点（P）下一级节点最大的右值 maxRight 最大右值：maxLeft
            Integer maxLvChildVal = mapper.maxLvChildVal(parent);
            //如果maxRight==0表示P下还没有子节点
            if (maxLvChildVal == null || maxLvChildVal == 0) {
                //>=右节点的所有左右节点+2
                mapper.updateLftAddVal(parent.getLft());
                mapper.updateRgtAddVal(parent.getLft());
                record.setLft(parent.getRgt());
                record.setRgt(parent.getRgt() + 1);
            } else {
                //>右节点的所有左右节点+2
                mapper.updateLftAddVal(maxLvChildVal);
                mapper.updateRgtAddVal(maxLvChildVal);
                record.setLft(maxLvChildVal + 1);
                record.setRgt(maxLvChildVal + 2);
            }
            record.setLevel(parent.getLevel() + 1);
            String parentIds = parent.getIds();
            if (StringUtils.isEmpty(parentIds)){
                record.setIds(String.valueOf(parent.getId()));
            } else {
                record.setIds(parentIds + "," + parent.getId());
            }
        }*/

        record.setCreateTime(new Date());
        int result = mapper.insert(record);
        if (result > 0) {
            return record;
        }
        return null;
    }

    //@LRTreeDelete(tableName = "tree")
    @Override
    public int delete(Long id) {
        /*Tree tree = mapper.findById(id);
        Integer lft = tree.getLft();
        Integer rgt = tree.getRgt();
        List<Integer> childIds = mapper.findChildIds(tree);
        if (CollectionUtils.isEmpty(childIds)) {
            //1、没有子节点
            mapper.updateLftSubVal(rgt, 2);
            mapper.updateRgtSubVal(rgt, 2);
        } else {
            Tree parent = mapper.findById(tree.getPid());
            Integer parentRgt = parent.getRgt();
            Integer minBrotherLftVal = mapper.minBrotherLftVal(parent, id);
            if (minBrotherLftVal == null || minBrotherLftVal == 0) {
                //2、有子节点 && 没有兄弟节点
                mapper.updateLftSubVal(rgt, parentRgt - lft);
                mapper.updateRgtSubVal(rgt, parentRgt - lft);
            } else {
                //3、有子节点 && 有兄弟节点
                mapper.updateLftSubVal(rgt, minBrotherLftVal - lft);
                mapper.updateRgtSubVal(rgt, minBrotherLftVal - lft);
            }
        }
        if (!CollectionUtils.isEmpty(childIds)){
            mapper.batchDeleteById(childIds);
        }*/
        //级联删除下级
        Tree current = mapper.findById(id);
        if (current.getRgt() - current.getLft() > 1) {
            //有子节点
            int result = mapper.deleteChildrenCascade(current.getLft(), current.getRgt());
        }
        mapper.deleteById(id);
        return 0;
    }

    @Override
    public List<Tree> findByPid(Long pid) {

        return mapper.findByPid(pid);
    }

    @Override
    public List<Tree> findByPidCascaded(Long pid) {
        Tree parent = mapper.findById(pid);
        if (parent == null) {
            return Collections.emptyList();
        }
        List<Tree> treeList = mapper.findByLftAndRgt(parent.getLft(), parent.getRgt());
        if (CollectionUtils.isEmpty(treeList)) {
            return Collections.emptyList();
        }
        return TreeUtil.converListToTree(treeList);
    }

}